import {defineConfig, loadEnv} from 'vite'

import vue from "@vitejs/plugin-vue";

const {resolve} = require('path')
import {basePath} from "./src/config/env";


export default ({mode, command}) => {
    const env = loadEnv(mode, process.cwd())
    const {VITE_APP_BASE} = env
    return defineConfig({
        base: VITE_APP_BASE === 'production' ? '/' : '/',
        resolve: {
            alias: {
                '~': resolve(__dirname, './'),
                "@": resolve(__dirname, "./src"),
                'views': resolve(__dirname, './src/views'),
                "components": resolve(__dirname, "./src/components"),
                "styles": resolve(__dirname, "./src/styles"),
                "utils": resolve(__dirname, "./src/utils"),
            },
            extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
        },
        plugins: [
            vue(),
            filterSassWarnings()
        ],
        server: {
            port: 9010,
            proxy: {
                '/api': {
                    target: "http://" + basePath + "/",
                    ws: true,            // 启用 WebSocket 代理
                    changeOrigin: true,  // 允许跨域
                    rewrite: (path) => path.replace(/^\/api/, '')
                }
            }
        },
        // https://blog.csdn.net/weixin_45732091/article/details/131783121
        // build: {
        //     outDir: "dist",
        //     assetsDir: "assets",
        //     rollupOptions: {
        //         // 配置打包输出路径
        //         output: {
        //             dir: 'dist', // 修改为你的实际输出目录
        //         },
        //         // 配置要包含的入口文件
        //         input: "src/main.js"
        //     },
        // },
    })
}

function filterSassWarnings() {
    return {
        name: 'filter-sass-warnings',
        apply: 'serve', // 或 'build' 或两者都写
        configResolved() {
            const originalWrite = process.stderr.write
            process.stderr.write = function (chunk, encoding, cb) {
                const str = typeof chunk === 'string' ? chunk : chunk.toString()
                if (str.indexOf('legacy-js-api') !== -1){
                    return true;
                } else{
                    return originalWrite.call(process.stderr, chunk, encoding, cb);
                }
            }
        }
    }
}